from helpFunc import *
import os,time,json
import sys

from collections import deque
runningPath = os.path.split(os.path.realpath(__file__))[0]
print (runningPath)  
mySalt = serviceSaltKey.encode()
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('0.0.0.0',servicePort))
usedMap = {}
usedQ = deque()
import uuid
while True:
    data, addr = sock.recvfrom(recLen)
    uuid2 ,ss = checkPackValid_server(data,mySalt)
    if not uuid2 :
        continue
    re = structWrapper(ss)
    sign = re.readArr(32).decode()
    m = {}

    m['rate'] = re.readDouble()
    m['pushAhead'] = re.readWord()
    m['packLimit'] = re.readWord()
    m['salt'] = re.readArr(6).decode()
    m['num'] = re.readWord()
  
    num = m['num']
    r = ''
    if sign not in usedMap:
        fileId = str(uuid.uuid1())
        savePath = runningPath+'/'+fileId
        m['savePath'] = savePath
        import base64,json
        j = json.dumps(m)
        s = base64.b64encode(j.encode())
        ex = sys.executable
        os.system('nohup %s %s/conns.py %s >/dev/null &'%(ex,runningPath,s.decode()))
        time.sleep(2)
        f = open(savePath)
        j = f.read()
        f.close()
        os.system('rm '+savePath)
        ports = json.loads(j)
        print ('start server:',ports)
        import struct
        re = b''
        for one in ports:
            re+= struct.pack('h',int(one)-65536//2)
        m2 = {'con':re,'createTime':getRunningTime()}
        usedMap[sign] = m2
        usedQ.append(sign)
        if len(usedMap)>10000:
            ss = usedQ.popleft()
            del usedMap[ss]
            
    m = usedMap[sign]
    j = m['con']
    data = makePack_server(j, uuid2, mySalt)
    sock.sendto(data,addr)
